<template>
  <div class="qa-container">
    <!-- 头部区域 -->
    <div class="header-container">
      <div class="emergency-header">
        <div class="black-block"></div>
        <div class="red-title">
          <el-icon><QuestionFilled /></el-icon>
          寻亲问答
        </div>
      </div>
      <div class="action-box">
        <el-button type="danger" @click="showQuestionForm">
          <el-icon><Plus /></el-icon> 提问
        </el-button>
        <div class="search-box">
          <el-input
            v-model="searchQuery"
            placeholder="搜索问题..."
            clearable
            @keyup.enter="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </div>
      </div>
    </div>

    <!-- 问答列表 -->
    <div class="list-container">
      <div v-if="loading" class="loading-container">
        <el-icon class="loading-icon"><Loading /></el-icon>
        加载中...
      </div>

      <template v-else>
        <div
          v-for="question in filteredQuestions"
          :key="question.id"
          class="qa-card"
        >
          <div class="qa-main" @click="showDetail(question)">
            <div class="qa-header">
              <div class="qa-title">{{ question.title }}</div>
            </div>

            <div class="qa-meta">
              <span class="author">{{ question.author }}</span>
              <span class="date">{{ question.date }}</span>
            </div>

            <div class="qa-preview">
              {{ question.content.substring(0, 100) }}...
            </div>
          </div>
          <div class="status-and-response">
            <div class="status-tag">
              <el-tag :type="question.resolved ? 'success' : 'warning'">
                {{ question.resolved ? '已解决' : '讨论中' }}
              </el-tag>
            </div>
            <div class="response-count">
              <el-icon><ChatDotRound /></el-icon>
              {{ question.answers.length }} 个回答
            </div>
          </div>
        </div>

        <div v-if="!filteredQuestions.length" class="empty-state">
          <el-icon class="empty-icon"><List /></el-icon>
          <p>暂无相关问题</p>
        </div>
      </template>
    </div>

    <!-- 提问弹窗 -->
    <el-dialog
      v-model="formVisible"
      title="提出新问题"
      width="600px"
    >
      <el-form :model="newQuestion" label-width="80px">
        <el-form-item label="问题标题" required>
          <el-input v-model="newQuestion.title" />
        </el-form-item>
        <el-form-item label="详细描述" required>
          <el-input
            v-model="newQuestion.content"
            type="textarea"
            :rows="4"
          />
        </el-form-item>
        <el-form-item label="添加标签">
          <el-select
            v-model="newQuestion.tags"
            multiple
            filterable
            allow-create
            placeholder="请输入或选择标签"
          >
            <el-option
              v-for="tag in commonTags"
              :key="tag"
              :label="tag"
              :value="tag"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="formVisible = false">取消</el-button>
        <el-button type="primary" @click="submitQuestion">提交</el-button>
      </template>
    </el-dialog>

    <!-- 详情弹窗 -->
    <el-dialog
      v-model="detailVisible"
      class="detail-dialog"
      width="800px"
    >
      <div class="dialog-header">
        <div class="header-content">
          <div class="dialog-title">{{ currentQuestion.title }}</div>
          <div class="status-info">
            <el-tag :type="currentQuestion.resolved ? 'success' : 'warning'">
              {{ currentQuestion.resolved ? '已解决' : '讨论中' }}
            </el-tag>
          </div>
        </div>
        <div class="meta-info">
          <span class="author">{{ currentQuestion.author }}</span>
          <span class="date">{{ currentQuestion.date }}</span>
        </div>
      </div>

      <div class="question-content">
        {{ currentQuestion.content }}
        <div class="tags-container">
          <el-tag
            v-for="tag in currentQuestion.tags"
            :key="tag"
            type="info"
            class="tag-margin"
          >
            {{ tag }}
          </el-tag>
        </div>
      </div>

      <div class="answers-section">
        <h3>回答（{{ currentQuestion.answers.length }}）</h3>

        <div class="answer-form">
          <el-input
            v-model="newAnswer"
            type="textarea"
            :rows="3"
            placeholder="写下你的回答..."
          />
          <div class="form-actions">
            <el-button type="primary" @click="submitAnswer">提交回答</el-button>
          </div>
        </div>

        <div
          v-for="answer in currentQuestion.answers"
          :key="answer.id"
          class="answer-card"
          :class="{ 'best-answer': answer.isBest }"
        >
          <div class="answer-header">
            <div class="user-info">
              <span class="username">{{ answer.author }}</span>
              <span class="role-tag" v-if="answer.isAuthor">提问者</span>
              <span class="date">{{ answer.date }}</span>
            </div>
            <div class="answer-actions">
              <el-button
                v-if="!currentQuestion.resolved && isQuestionAuthor"
                type="success"
                size="small"
                @click="markBestAnswer(answer)"
              >
                采纳答案
              </el-button>
              <div class="like-button" @click="toggleLike(answer)">
                <el-icon :class="{ 'liked': answer.isLiked }"><Star /></el-icon>
                {{ answer.likes }}
              </div>
            </div>
          </div>
          <div class="answer-content">{{ answer.content }}</div>

          <!-- 回复列表 -->
          <div v-if="answer.replies.length" class="replies-container">
            <div
              v-for="reply in answer.replies"
              :key="reply.id"
              class="reply-card"
            >
              <div class="reply-header">
                <span class="username">{{ reply.author }}</span>
                <span class="date">{{ reply.date }}</span>
              </div>
              <div class="reply-content">{{ reply.content }}</div>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import {
  QuestionFilled,
  Search,
  Plus,
  Loading,
  List,
  ChatDotRound,
  Star
} from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

interface Question {
  id: number
  title: string
  content: string
  author: string
  date: string
  tags: string[]
  resolved: boolean
  answers: Answer[]
}

interface Answer {
  id: number
  content: string
  author: string
  date: string
  likes: number
  isLiked: boolean
  isBest: boolean
  isAuthor: boolean
  replies: Reply[]
}

interface Reply {
  id: number
  content: string
  author: string
  date: string
}

// 响应式数据
const searchQuery = ref('')
const loading = ref(true)
const formVisible = ref(false)
const detailVisible = ref(false)
const currentQuestion = ref<Question>({} as Question)
const questions = ref<Question[]>([])
const newQuestion = ref({
  title: '',
  content: '',
  tags: [],
  author: '当前用户'
})
const newAnswer = ref('')
const commonTags = ref(['走失特征', '寻找技巧', '法律咨询', '救援经验', '儿童走失'])

// 计算属性
const filteredQuestions = computed(() => {
  const query = searchQuery.value.toLowerCase()
  return questions.value.filter(q =>
    q.title.toLowerCase().includes(query) ||
    q.content.toLowerCase().includes(query) ||
    q.tags.some(tag => tag.toLowerCase().includes(query))
  )
})

const isQuestionAuthor = computed(() => {
  return currentQuestion.value.author === '当前用户'
})

// 方法
const showQuestionForm = () => {
  formVisible.value = true
}

const handleSearch = () => {
  console.log('执行搜索:', searchQuery.value)
}

const submitQuestion = () => {
  questions.value.unshift({
    id: Date.now(),
    ...newQuestion.value,
    date: new Date().toLocaleDateString(),
    resolved: false,
    answers: []
  })
  formVisible.value = false
  ElMessage.success('问题提交成功')
  newQuestion.value = { title: '', content: '', tags: [], author: '当前用户' }
}

const submitAnswer = () => {
  if (!newAnswer.value.trim()) return

  const answer: Answer = {
    id: Date.now(),
    content: newAnswer.value,
    author: '热心网友',
    date: new Date().toLocaleString(),
    likes: 0,
    isLiked: false,
    isBest: false,
    isAuthor: false,
    replies: []
  }

  currentQuestion.value.answers.push(answer)
  newAnswer.value = ''
  ElMessage.success('回答提交成功')
}

const toggleLike = (answer: Answer) => {
  answer.isLiked = !answer.isLiked
  answer.likes += answer.isLiked ? 1 : -1
}

const markBestAnswer = (answer: Answer) => {
  currentQuestion.value.answers.forEach(a => a.isBest = false)
  answer.isBest = true
  currentQuestion.value.resolved = true
  ElMessage.success('已标记为最佳答案')
}

const showDetail = (question: Question) => {
  currentQuestion.value = { ...question }
  detailVisible.value = true
}

// 模拟数据
onMounted(() => {
  setTimeout(() => {
    questions.value = [
      {
        id: 1,
        title: '寻找走失老人需要注意哪些法律程序？',
        content: '家中老人患有阿尔茨海默病，于昨日走失。具体情况是:老人今年75岁,身高165cm,穿着蓝色上衣和黑色裤子,走失时间是昨天下午3点左右,最后出现在小区门口。请问报警和发布寻人启事需要注意哪些法律要求？如何能更快找到老人？',
        author: "张女士",
        date: '2023-08-20',
        tags: ['法律咨询', '老人走失', '阿尔茨海默病'],
        resolved: false,
        answers: [
          {
            id: 1,
            content: '根据《失踪人口救助法》,您应该立即采取以下措施:\n1. 向当地公安机关报案,准备以下材料:\n- 走失者近期照片\n- 身份证复印件\n- 详细体貌特征描述\n- 走失时着装信息\n- 可能去往的地点\n2. 联系社区网格员和物业,调取监控录像\n3. 发动亲友帮忙寻找,重点关注:\n- 老人经常去的场所\n- 医院、公园等公共场所\n- 交通枢纽\n4. 在社交媒体发布寻人信息时注意:\n- 信息准确完整\n- 避免过度暴露个人隐私\n- 及时更新进展\n\n建议您同时联系当地的老年救助机构获取帮助。',
            author: "法律援助",
            date: '2023-08-20 14:30',
            likes: 12,
            isLiked: false,
            isBest: false,
            isAuthor: true,
            replies: []
          },
          {
            id: 2,
            content: '在报警时，确保提供详细的走失者信息，包括身高、体重、穿着等特征。此外，您可以联系当地的志愿者组织，他们通常会提供帮助和支持。',
            author: "社区志愿者",
            date: '2023-08-20 15:00',
            likes: 5,
            isLiked: false,
            isBest: false,
            isAuthor: false,
            replies: []
          }
        ]
      },
      {
        id: 2,
        title: '如何有效寻找走失儿童？寻找过程中需要注意什么？',
        content: '我的侄子今年6岁,在商场走失了。他身高120cm,穿着红色T恤和牛仔裤,走失前最后在商场三楼玩具区看到。请问在寻找走失儿童时,除了报警外还有哪些有效的方法和注意事项？如何预防类似事件再次发生？',
        author: "李先生",
        date: '2023-08-21',
        tags: ['儿童走失', '寻找技巧', '安全预防'],
        resolved: false,
        answers: [
          {
            id: 1,
            content: '寻找走失儿童时，首先要保持冷静，迅速回忆最后看到孩子的地点，并询问周围的人。可以在商场内广播寻人信息，同时联系商场的安保人员进行协助。',
            author: "儿童安全专家",
            date: '2023-08-21 10:00',
            likes: 8,
            isLiked: false,
            isBest: false,
            isAuthor: false,
            replies: []
          },
          {
            id: 2,
            content: '在日常生活中，家长可以给孩子佩戴带有联系方式的手环，教导他们在走失时如何寻求帮助，比如找工作人员或警察。',
            author: "心理咨询师",
            date: '2023-08-21 10:30',
            likes: 6,
            isLiked: false,
            isBest: false,
            isAuthor: false,
            replies: []
          }
        ]
      },
      {
        id: 3,
        title: '走失事件后如何帮助家人和走失者调节心理状态？',
        content: '我的父亲上周因为记忆障碍走失了24小时后被找到。虽然人已平安,但他变得很自闭,总是情绪低落。我们家人也都很自责和焦虑。请问走失后,家属和走失者应该如何调节心理状态？需要寻求专业心理咨询吗？',
        author: "王小姐",
        date: '2023-08-22',
        tags: ['心理咨询', '家庭关怀', '走失康复'],
        resolved: false,
        answers: []
      },
      {
        id: 4,
        title: '走失人员在法律上的相关问题咨询',
        content: '如果走失人员在走失期间造成他人损失或发生意外,是否需要承担法律责任？家属有什么责任和义务？另外,如何申请走失人员的临时监护？请详细说明相关法律程序。',
        author: "赵先生",
        date: '2023-08-23',
        tags: ['法律咨询', '监护责任', '损害赔偿'],
        resolved: false,
        answers: []
      },
      {
        id: 5,
        title: '向警方报案的流程和注意事项咨询',
        content: '想详细了解以下问题:\n1. 走失多久可以报案？是否要等24小时？\n2. 报案需要准备哪些材料？\n3. 如何与警方保持有效沟通？\n4. 寻人启事发布有什么规范要求？\n5. 找到人后需要办理哪些手续？',
        author: "钱女士",
        date: '2023-08-24',
        tags: ['法律咨询', '报警程序', '寻人启事'],
        resolved: false,
        answers: []
      }
    ]
    loading.value = false
  }, 800)
})
</script>

<style scoped>
.qa-container {
  padding: 20px;
  margin: 0 auto;
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.header-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  gap: 20px;
  margin-top: 20px;
  flex-shrink: 0;
}

.emergency-header {
  display: flex;
  height: 50px;
  border-radius: 6px;
  overflow: hidden;
  flex-shrink: 0;
}

.black-block {
  width: 10px;
  background: var(--reverse-background-color);
}

.red-title {
  flex: 1;
  background: #f45c5c;
  color: white;
  display: flex;
  align-items: center;
  padding: 0 20px;
  font-size: 22px;
  font-weight: 600;
  gap: 10px;
}

.action-box {
  display: flex;
  gap: 20px;
  align-items: center;
}

.qa-card {
  position: relative;
  margin-bottom: 16px;
  border-radius: 8px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  transition: all 0.3s;
  cursor: pointer;
  border: 1px solid;
  text-align: left;
  height: 230px;
  display: flex;
  flex-direction: column;
  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0,0,0,0.15);
  }
}

.qa-main {
  flex: 1;
}

.qa-header {
  margin-bottom: 12px;
}

.qa-title {
  font-size: 18px;
  font-weight: 500;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.qa-meta {
  display: flex;
  justify-content: center;
  gap: 12px;
  margin: 8px 0;
  font-size: 13px;
}

.qa-preview {
  line-height: 1.6;
  font-size: 14px;
  height: 6.4em;
  overflow: hidden;
  text-align: left;
  text-indent: 2ch;
  margin-top: 10px;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 4;
}

.status-and-response {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 10px;
}

.status-tag {
  margin-right: 10px;
}

.response-count {
  display: flex;
  align-items: center;
}

.detail-dialog {
  .dialog-header {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-bottom: 20px;

    .header-content {
      display: flex;
      justify-content: space-between;
      width: 100%;
      align-items: center;
    }

    .dialog-title {
      font-size: 24px;
      font-weight: bold;
      text-align: center;
      flex: 1;
    }

    .meta-info {
      display: flex;
      gap: 20px;
      margin-top: 10px;
    }
  }
  .question-content {
    padding: 20px 0;
    line-height: 1.8;
    border-bottom: 1px solid #eee;
  }

  .answers-section {
    margin-top: 24px;

    h3 {
      margin-bottom: 16px;
    }
  }
}

.answer-card {
  padding: 16px;
  margin-bottom: 16px;
  border: 1px solid ;
  border-radius: 6px;

  &.best-answer {
    border-left: 3px solid #67c23a;
  }
}

.answer-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 12px;

  .user-info {
    color: #666;

    .role-tag {
      color: #409eff;
      padding: 2px 6px;
      border-radius: 3px;
      font-size: 12px;
      margin: 0 8px;
    }
  }
}

.answer-actions {
  display: flex;
  gap: 12px;
  align-items: center;

  .like-button {
    display: flex;
    align-items: center;
    gap: 4px;
    color: #666;
    cursor: pointer;

    &:hover {
      color: #9b2a2a;
    }

    .liked {
      color: #9b2a2a;
    }
  }
}

.reply-card {
  margin-top: 12px;
  padding: 8px;
  border-radius: 4px;
  font-size: 13px;

  .reply-header {
    margin-bottom: 4px;
  }
}

.answer-form {
  margin-bottom: 24px;

  .form-actions {
    margin-top: 12px;
    text-align: right;
  }
}

.list-container {
  flex: 1;
  overflow-y: auto;
  padding-right: 10px;
}
</style>
